package com.hange.ymcc.exception;


import com.hange.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器

 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public JSONResult businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return JSONResult.error(e.getMessage(),e.getCode());
    }

    @ExceptionHandler(RuntimeException.class)
    public JSONResult runtimeExceptionHandler(RuntimeException e) {
        //AccessDeniedException
        if(e.getClass().getSimpleName()=="AccessDeniedException")
            return JSONResult.error("权限不足",ErrorCode.NO_AUTH.getCode());

        log.error("runtimeException", e);
        return JSONResult.error("系统出错了",ErrorCode.SYSTEM_ERROR.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("methodArgumentNotValidException", e);
        List<ObjectError> Errors = e.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        for (ObjectError error : Errors) {
            errorMsg.append(error.getDefaultMessage());
            if(error != Errors.get(Errors.size()-1))
                errorMsg.append(",");
        }
        return JSONResult.error(errorMsg.toString(),ErrorCode.PARAMS_ERROR.getCode());
    }
}
